package com.stylefeng.guns.modular.pay.validator;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;
import com.stylefeng.guns.core.util.MD5Utils;
import com.stylefeng.guns.modular.pay.model.MchInfo;
import com.stylefeng.guns.modular.pay.service.IMchInfoService;

/**
 * 请求参数验签
 * 
 * @author DevinYang
 * @date 2018年5月29日
 *
 */
@Component
public class SignVerifyValidator extends ValidatorHandler<Map<String,String>> implements Validator<Map<String,String>> {
	private final static Logger log = LoggerFactory.getLogger(SignVerifyValidator.class);
	@Autowired
	private IMchInfoService mchInfoService;
	
	@Override
	public boolean validate(ValidatorContext context, Map<String,String> reqMap) {
		if(!reqMap.containsKey("sign")){
			context.addErrorMsg(String.format("sign参数为空"));
			return false;
		}
		String mchNo = reqMap.get("mchNo");
		MchInfo mch = mchInfoService.findByMchNo(mchNo);
		if(mch==null){
			context.addErrorMsg(String.format("商户不存在%s",mchNo));
			return false;
		}
		String sign = reqMap.get("sign");
	    Boolean flag = false;
	    try {
	    	flag = MD5Utils.verify(reqMap, sign, mch.getMd5Key(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
	    if(!flag){
	    	context.addErrorMsg(String.format("请求参数验签失败"));
			return false;
	    }
	   return true;
	}

}
